<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-06-28 09:54
 * Modified Time: 2019-06-28 09:54
 * Version: 2.0
 */

namespace App\Modules\Order\Repositories;


use App\Models\OrderItem;
use App\Modules\Order\Criterias\findServiceTypeOrderListCriteria;
use App\Modules\Order\Criterias\getOrderServiceListCriteria;
use App\Modules\Order\Validators\OrderItemValidator;
use Flower\Core\Repository\Eloquent\BaseRepository;
use Illuminate\Support\Facades\DB;

class OrderItemRepository extends BaseRepository
{

	public function model()
	{
		// TODO: Implement model() method.
		return OrderItem::class;
	}

	public function validator()
	{
		return OrderItemValidator::class; // TODO: Change the autogenerated stub
	}

	/**
	 * 新增记录
	 * @param $requestData
	 * @return mixed
	 */
	public function add($orderId, $service = [], $requestData)
	{
		$data = [
			'order_id'     => $orderId,
			'service_id'   => !empty($service) ? $service['id'] : 0,
			'service_name' => !empty($service) ? $service['name'] : '',
			'price'        => !empty($service) ? round($service['price'], 1) : 0,
			'real_price'   => isset($requestData['real_price']) ? round(intval($requestData['real_price']) / (isset($requestData['count']) ? $requestData['count'] : 1), 1) : 0,
			'count'        => isset($requestData['count']) ? $requestData['count'] : 1,
		];
		return $this->create($data);
	}

	/**
	 * 批量插入
	 * @param $data
	 * @return mixed
	 */
	public function insertAll($data)
	{
		return $this->model->insert($data);
	}


	/**
	 * 新增订单的附属清单
	 * @param $orderId
	 * @param $serviceId
	 * @param $serviceName
	 * @param $servicePrice
	 * @param $realPrice
	 * @param int $count
	 * @return mixed
	 */
	public function addOrderItemInfo($orderId, $serviceId, $serviceName, $servicePrice, $realPrice, $count, $barberid, $assistantId)
	{
		$count = isset($count) ? $count : 1;
		$data = [
			'order_id'     => $orderId,
			'service_id'   => $serviceId,
			'service_name' => $serviceName,
			'price'        => $servicePrice,
			'real_price'   => round($realPrice / $count, 2),
			'count'        => $count
		];

		$info = $this->findWhere([
			'order_id'     => $orderId,
			'service_id'   => $serviceId,
			'service_name' => $serviceName,
			'price'        => $servicePrice
		])->first();
		if (!empty($info)) {
			$info->real_price = round($realPrice / $count, 2);
			$info->count = $count;
			$info->save();
		} else {
			$info = $this->create($data);
		}
		return $info;
	}


	/**
	 * 订单服务数据排名
	 * @param $storeId
	 * @param $startDate
	 * @param $endDate
	 * @param int $isAmount
	 * @return mixed
	 */
	public function getOrderServiceAmountCount($storeId, $startDate, $endDate, $isAmount = 1, $isLimit = 1, $user_id = null)
	{
		$list = $isAmount ? $this->model->selectRaw('sum(real_price*count) as counts, service_id, service_name') :
			$this->model->selectRaw('count(id) as counts, service_id, service_name');

		$newList = $list->whereHas('order', function ($query) use ($storeId, $user_id) {
			$query->where(['store_id' => $storeId, 'status' => 2])
				->when($user_id, function ($query) use ($user_id) {
					$query->where(['barber_id' => $user_id]);
				});
		})
			->whereRaw('date(created_at) >= "' . $endDate . '" and date(created_at) <= "' . $startDate . '"')
			->groupBy('service_id')
			->orderByDesc('counts');
		$isLimit ? $newList->take(5) : $newList;
		return $newList->get();
	}


	/**
	 * 获取订单服务列表
	 * @param $storeId
	 * @param $serviceId
	 * @param $startDate
	 * @param $endDate
	 * @param $pageSize
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getOrderServiceList($storeId, $serviceId, $startDate, $endDate, $pageSize, $user_id = null, $isProfit = 0)
	{
		$pageSize = isset($pageSize) ? $pageSize : 10;
		return $this->pushCriteria(new getOrderServiceListCriteria($storeId, $serviceId, $startDate, $endDate, $user_id, $isProfit))->paginate($pageSize, ['*'], 'paginate');
	}



//	public function getOrderBusinessData($dateList,$storeId){
//		$sql = 'select  count(i.`id`) as nums, s.`type`,sum(o.`real_price`) as amount,sum(o.`profit`) as profit
//from `hx_order_item` as i
//left join `hx_order` as o on i.`order_id`= o.`id` and o.`status`= 2
//left join `hx_store_service` as s on i.`service_id` = s.`id` and s.`deleted_at` is null
//where o.`store_id`="'.$storeId.'" and  FROM_UNIXTIME(o.`finish_time`,\'%Y-%m-%d\') >="'.$dateList['end_date'].'" and  FROM_UNIXTIME(o.`finish_time`,\'%Y-%m-%d\') <="'.$dateList['start_date'].'"  group by s.`type`';
//		return DB::select($sql);
//	}

	/**
	 * 经营数据分析
	 * @param $dateList
	 * @param $storeId
	 * @param $type
	 * @param int $pageSize
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getOrderServiceAmountList($dateList, $storeId, $type, $pageSize = 10)
	{
		return $this->pushCriteria(new findServiceTypeOrderListCriteria($dateList, $storeId, $type))->paginate($pageSize, ['*'], 'paginate');
	}

	/**
	 * @param $orderIds
	 * @return mixed
	 */
	public function getListByOrderIds($orderIds)
	{
		return $this->model->whereIn('order_id', $orderIds)->orderBy('created_at', 'desc')->get()->toArray();
	}


	public function getOrderStatisticsByStoreIdAndField($storeId, $field, $type, $oneField, $twoField)
	{
		if ($field == 'appointment_id' || $field == 'member_card_id') {
			$whereOne = [$field => ['>', 0]];
			$whereTwo = [$field => ['=', 0]];
			$one = $this->model->whereHas('order', function ($v) use ($field, $storeId, $whereOne) {
				$v->where(['order.status' => 2, 'order.store_id' => $storeId])->where($whereOne);
			})->whereDate('created_at',date('Y-m-d'));
			$two = $this->model->with([
				'orderMul' => function ($v) use ($field, $storeId, $whereTwo) {
					$v->where(['status' => 2, 'store_id' => $storeId])->where($whereTwo);
				}
			])->whereDate('created_at',date('Y-m-d'));
		} else {
			$whereOne = [$field => ['=', 1]];
			$whereTwo = [$field => ['=', 0]];
			$one = $this->model->whereHas('order', function ($v) use ($field, $storeId) {
				$v->where(['order.status' => 2, 'order.store_id' => $storeId]);
			})->where($whereOne)->whereDate('created_at',date('Y-m-d'));
			$two = $this->model->whereHas('order', function ($v) use ($field, $storeId) {
				$v->where(['status' => 2, 'store_id' => $storeId]);
			})->where($whereTwo)->whereDate('created_at',date('Y-m-d'));
		}
		// @todo价格合计重算
		return [
			$oneField => $type ? $one->count() : $one->sum('real_price'),
			$twoField => $type ? $two->count() : $two->sum('real_price'),
			'unit'    => $type ? '单' : '元',
		];
	}
}
